//
//  GroupRootViewController.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/2.
//

#import "GroupRootViewController.h"
#import "WKWebViewJavascriptBridge.h"
#import "BaseRequestApi.h"
#import <CoreLocation/CoreLocation.h>

@interface GroupRootViewController ()<WKNavigationDelegate,CLLocationManagerDelegate>

@property WKWebViewJavascriptBridge* bridge;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, retain) CLLocation *myLocation;
@property (nonatomic, strong) WKWebView* webView;

@property (nonatomic, copy) WVJBResponseCallback getLocationInfoBlock;

@property (nonatomic, strong) UIView *naviBarView;

@end

@implementation GroupRootViewController

- (UIView *)naviBarView {
    if (!_naviBarView) {
        _naviBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, NavigationBarHeight)];
        _naviBarView.backgroundColor = COLOR_WHITE;
        UILabel *titleLB = [[UILabel alloc] initWithFrame:CGRectMake(MARGIN_MAX, SafeAreaTopHeight, SCREEN_W-MARGIN_MAX*2, 44)];
        titleLB.text = CycLocalizedString(@"Ranking", @"排行榜");
        titleLB.textAlignment = NSTextAlignmentCenter;
        titleLB.textColor = rgbHex(0x222222, 1.0);
        titleLB.font = FONT_PRIMARY_TITLE;
        [_naviBarView addSubview:titleLB];
    }
    return _naviBarView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.naviBarView];
    
    [self startLocation];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_bridge) { return; }
    [self.navigationController setNavigationBarHidden:YES animated:NO];

    WKWebView* webView = [[NSClassFromString(@"WKWebView") alloc] initWithFrame:CGRectZero];
    [webView setOpaque:NO];
    webView.navigationDelegate = self;
    webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self loadExamplePage:webView];

    [self.view addSubview:webView];
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(self.view).offset(NavigationBarHeight);
        make.bottom.equalTo(self.view).offset(-60-SafeAreaBottomHeight);
    }];
    self.webView = webView;
    
    [WKWebViewJavascriptBridge enableLogging];
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView];
    [_bridge setWebViewDelegate:self];

    [_bridge registerHandler:@"loadUserInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSString *token = [USERDEFAULTS valueForKey:@"Token"];
        NSString *language = [[CycLanguage sharedInstance] currentLanguage];
        responseCallback(@{@"token":token,@"lang":language});
    }];
    [_bridge registerHandler:@"getTopHeight" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSString *height = [NSString stringWithFormat:@"%f",SafeAreaTopHeight];
        responseCallback(@{@"height":height});
    }];
    
    [_bridge registerHandler:@"onBackPress" handler:^(id data, WVJBResponseCallback responseCallback) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    //开始加载动画
    [_bridge registerHandler:@"showLoading" handler:^(id data, WVJBResponseCallback responseCallback) {
        [self showLoadingViewWithText:@""];
    }];
    //移除加载动画
    [_bridge registerHandler:@"hideLoading" handler:^(id data, WVJBResponseCallback responseCallback) {
        [self removeLoadingView];
    }];
    
    // 设置经纬度
    [_bridge registerHandler:@"getlocationInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        if(self.myLocation) {
            NSDictionary *locationInfo = @{@"lng" : @(self.myLocation.coordinate.longitude), @"lat" : @(self.myLocation.coordinate.latitude)};
            if(responseCallback) {
                responseCallback(locationInfo);
            }
            self.myLocation = nil;
        } else {
            [self.locationManager requestLocation];
            self.getLocationInfoBlock = responseCallback;
        }
    }];
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidStartLoad");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidFinishLoad");
}

- (void)loadExamplePage:(WKWebView*)webView {
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:Cyc_WEBURL_GROUP]]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];

}

//开始定位
- (void)startLocation {
    //初始化定位管理者
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;

    //判断设备是否能够进行定位
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if ([CLLocationManager locationServicesEnabled]) {
            //精确度获取到米
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            //设置过滤器为无
            self.locationManager.distanceFilter = kCLDistanceFilterNone;
            // 取得定位权限，有两个方法，取决于你的定位使用情况
            //一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
            [self.locationManager requestWhenInUseAuthorization];
            //开始获取定位
            [self.locationManager startUpdatingLocation];
            //地理信息
    //        self.geoCoder = [[CLGeocoder alloc] init];
        } else {
            DebugLog(@"error");
        }
    });
}

//设置获取位置信息的代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    NSLog(@"%lu", (unsigned long)locations.count);
    self.myLocation = locations.lastObject;
    DebugLog(@"经度：%f 纬度：%f", _myLocation.coordinate.longitude, _myLocation.coordinate.latitude);
    
    //不用的时候关闭更新位置服务，不关闭的话这个 delegate 隔一定的时间间隔就会有回调
    [self.locationManager stopUpdatingLocation];
//    [self loadExamplePage:self.webView];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.getLocationInfoBlock) {
            NSDictionary *locationInfo = @{@"lng" : @(self.myLocation.coordinate.longitude), @"lat" : @(self.myLocation.coordinate.latitude)};
            self.getLocationInfoBlock(locationInfo);
            self.myLocation = nil;
        }
    });
}
//问题函数
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if (error) {
        DebugLog(@"error:%ld", (long)error.code);
    }
}


@end
